﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

using TidyNet;

namespace MyPublisher.Composition.XWord
{
    internal class HtmlTidy
    {
        internal static void Tidy(string htmlfile)
        {
            string inputfile = string.Empty;
            try
            {
                Tidy tidy = new Tidy();
                tidy.Options.Xhtml = true;
                tidy.Options.DocType = DocType.Omit;
                tidy.Options.EncloseBlockText = true;
                tidy.Options.CharEncoding = CharEncoding.UTF8;
                tidy.Options.SmartIndent = true;
                tidy.Options.NumEntities = true;
                //tidy.Options.XmlSpace = true;

                inputfile = Path.GetTempFileName();
                File.Copy(htmlfile, inputfile,true);

                string outputfile = htmlfile;
                using (Stream inputStream = new FileStream(inputfile, FileMode.Open, FileAccess.Read))
                using (Stream outputStream = new FileStream(outputfile, FileMode.Truncate, FileAccess.Write))
                {
                    TidyMessageCollection messages = new TidyMessageCollection();
                    tidy.Parse(inputStream, outputStream, messages);
                }
            }
            catch (Exception e)
            {
                throw new TransformException("Failed to tidy html file -" + htmlfile, e);
            }
            finally
            {
                try { File.Delete(inputfile); }
                catch { };
            }
        }
    }
}
